from django.shortcuts import render, HttpResponse, redirect, reverse

# Create your views here.
# 引入所有已经创建的数据库类型
from app1.models import *


def index(request):
    """
    主页
    :param request:
    :return:渲染主页面
    """
    user_list = User.objects.all()
    context = {'user_list': user_list}
    return render(request, 'index.html', context)


def add_user(request):
    """
    添加页面
    :param request:
    :return:GET请求渲染添加页面，POST请求重定向到主页面
    """
    # 方式一
    # user = User()
    # user.username = 'acc'
    # user.password = '123'
    # user.gender = 2
    # user.new = '22'
    # user.age = 18
    # user.save()
    # print('ok')
    # 方式二
    # user = 'acc'
    # password = '123'
    # gender = 2
    # new = '22'
    # age = 18
    # User.objects.create(user=user, password=password, gender=gender, new=new, age=age)
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        gender = request.POST.get('gender')
        new = request.POST.get('new')
        age = request.POST.get('age')
        User.objects.create(username=username, password=password, gender=gender, new=new, age=age)
        return redirect(reverse('user:index'))
    else:
        return render(request, 'add_user.html')


def edit_user(request, edit_user_id):
    """
    编辑用户
    :param request:
    :param edit_user_id:
    :return:GET请求渲染编辑页面，POST请求重定向到index主页
    """
    if request.method == "GET":
        user_list = User.objects.filter(id=edit_user_id).first()
        context = {'user_list': user_list}
        return render(request, 'edit_html.html', context)
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        gender = request.POST.get('gender')
        new = request.POST.get('new')
        age = request.POST.get('age')
        User.objects.create(username=username, password=password, gender=gender, new=new, age=age)
        return redirect(reverse('user:index'))


def del_user(request, del_user_id):
    """
    删除用户
    :param request:主要是GET请求
    :param del_user_id:要删除用户的Id
    :return:重定向到index主页
    """
    User.objects.filter(id=del_user_id).delete()
    return redirect(reverse('user:index'))
